package licode.unisop.realm.application.executor;

import licode.unisop.provider.info.*;
import licode.unisop.realm.application.gateway.SiRealmModelGateway;
import licode.unisop.realm.application.gateway.SiUserProviderManager;
import licode.unisop.realm.application.service.SiAuthenticationInterceptorUrl;
import licode.unisop.realm.application.service.SiAuthenticationProviderUrl;
import licode.unisop.realm.application.service.SiRestfulCallUtil;
import licode.unisop.realm.client.api.SiIdentityService;
import licode.unisop.realm.client.info.SiIdentityRegister;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class SiIdentityExecutor implements SiIdentityService {
    @Resource
    private SiRestfulCallUtil siRestfulCallUtil;

    @Resource
    private SiUserProviderManager siUserProviderManager;

    @Resource
    private SiRealmModelGateway siRealmModelGateway;

    @Override
    public SiReturnCode authUser(SiIdentityContext context) {
        return siUserProviderManager.findAuthProvider(SiIdentityFind.builder()
                        .authType(context.getExist().getAuthType())
                        .realmId(context.getRealmId())
                        .platformId(context.getPlatformId())
                        .build())
                .authenticate(context);
    }

    @Override
    public void registerIdentityPlugin(SiIdentityRegister regInfo) {
        siUserProviderManager.registerAuthProvider(SiAuthenticationReg
                .builder()
                .authType(regInfo.getAuthType())
                .realmId(regInfo.getRealmId())
                .provider(new SiAuthenticationProviderUrl(siRestfulCallUtil,
                        SiUrlProviderInfo.builder()
                                .url(regInfo.getUrl())
                                .name(regInfo.getName())
                                .comment(regInfo.getComment())
                                .build()))
                .build());
    }

    @Override
    public void registerIdentityInterceptor(SiIdentityRegister regInfo) {
        siUserProviderManager.registerAuthInterceptor(SiAuthInterceptorReg
                .builder()
                .realmId(regInfo.getRealmId())
                .platformId(regInfo.getPlatformId())
                .plugin(new SiAuthenticationInterceptorUrl(siRestfulCallUtil, regInfo.getUrl()))
                .build());
    }
}
